package library.web.servlet.other;

import library.domain.User;
import library.persistence.dao.MessageDao;
import library.persistence.impl.MessageDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "deleteMessageServlet",urlPatterns = {"/deleteMessage"})
public class DeleteMessageServlet extends HttpServlet {
    private String username;
    private String time;


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.username = req.getParameter("username");
        this.time = req.getParameter("time");
        MessageDao messageDao = new MessageDaoImpl();
        HttpSession session = req.getSession();
        if(session.getAttribute("deleteMsg") != null){
            session.setAttribute("deleteMsg",null);
        }
        User loginUser = (User)session.getAttribute("loginUser");
        if(loginUser == null){
            if(this.username.equals("visitor")){
                messageDao.deleteMessageByTime(this.time);
            }else{
                session.setAttribute("deleteMsg","只能删除自己的留言");
            }
        }else if(loginUser.getIsManager() == 1){
            messageDao.deleteMessageByTime(this.time);
        }else{
            if(loginUser.getUsername().equals(this.username)){
                messageDao.deleteMessageByTime(this.time);
            }else{
                session.setAttribute("deleteMsg","只能删除自己的留言");
            }
        }

        resp.sendRedirect("message");
    }
}
